package com.njwb.day15.dao.impl;

import com.njwb.day15.dao.StudentDao;
import com.njwb.day15.pojo.Student;
import com.njwb.day15.util.JdbcTemplate;

import java.sql.SQLException;
import java.util.List;

public class StudentDaoImpl implements StudentDao {
    @Override
    public int addStudent(Student stu) throws SQLException {
        return JdbcTemplate.executeUpdate("insert into tb_student(sname,age,address) values(?,?,?)", stu.getSname(), stu.getAge(), stu.getAddress());
    }

    @Override
    public int updateStudent(Student stu) throws SQLException {
        return JdbcTemplate.executeUpdate("update tb_student set sname= ? ,age=?,address=? where sid=?", stu.getSname(), stu.getAge(), stu.getAddress(), stu.getSid());
    }

    @Override
    public int deleteStudentById(int sid) throws SQLException {
        return JdbcTemplate.executeUpdate("delete from tb_student where sid =?", sid);
    }

    @Override
    public Student findStudentById(int sid) throws SQLException {
        return JdbcTemplate.executeQueryOne("select sid,sname,age,address from tb_student where sid=?", r -> {
            return new Student(r.getInt(1), r.getString(2), r.getInt(3), r.getString(4));
        }, sid);
    }

    @Override
    public List<Student> queryAllStudents() throws SQLException {
        return JdbcTemplate.executeQueryAll("select sid,sname,age,address from tb_student", r -> {
            return new Student(r.getInt(1), r.getString(2), r.getInt(3), r.getString(4));
        }, new Object[]{});

    }
}
